<?php

/**
 * Controller is the customized base controller class.
 * All controller classes for this application should extend from this base class.
 */
class Controller extends CController {

    /**
     * @var string the default layout for the controller view. Defaults to '//layouts/column1',
     * meaning using a single column layout. See 'protected/views/layouts/column1.php'.
     */
    public $layout = 'column3_1';
    protected $runAfterAction = true;

    /**
     * @var array context menu items. This property will be assigned to {@link CMenu::items}.
     */
    public $menu = array();

    /**
     * @var array the breadcrumbs of the current page. The value of this property will
     * be assigned to {@link CBreadcrumbs::links}. Please refer to {@link CBreadcrumbs::links}
     * for more details on how to specify this property.
     */
    public $breadcrumbs = array();
    public $showBackButton = false;
    public $useBootstrap = true;

    public function init() {
        parent::init();

        if (isset(Yii::app()->session['_lang'])) {
            Yii::app()->language = Yii::app()->session['_lang'];
        }

        //user must login before enter site
        if (Yii::app()->user->isGuest) {
            //if redirect from wechat
            if ((isset($_GET['device']) && (strtolower($_GET['device']) == 'wechat' || strtolower($_GET['device']) == 'weixin')) ||
                    (isset($_GET['dv']) && strtolower($_GET['dv']) == 'wx')) {
                $parsedData = BUIWXControl::parseWeChatInfo();
                /*
                  if (isset($parsedData['group']) && $parsedData['group'] == '97Sports') {
                  //if no account is created with wechat info, create one
                  $userId = 'user@97Sports.com';
                  $pwd = 'sadfsUdfsZ?@q23!';
                  $user = BUser::find(array('userName' => $userId));
                  if (!$user instanceof BUser) {
                  $profile['birthday'] = '01012099';
                  $profile['userName'] = "wechat";
                  $profile['email'] = $userId;
                  BUser::registerWechat($userId, $pwd, $profile);
                  }
                  BUser::login($userId, $pwd, 0);
                  }
                 * 
                 */

                if (isset($parsedData['wxSpace']) && $parsedData['wxSpace'] instanceof BSpace) {

                    /*
                     * 获取关注“重庆商社”的粉丝信息
                     */
                    //$get_user_list;
                    //$access_token_hamshun = "UpUr140mh5OjbqKd7ynMW5abVX94DImeLd4mSCtEugawjuZOn2GbssF-kEhIyZzv"; //access_token
                    //$userArrayDataOpenId = $this->get_user_list($access_token_hamshun);
                    //var_dump($userArrayDataOpenId);
                    // $userArrayOpenId = $userArrayDataOpenId["data"]["openid"];
                    //if no account is created with wechat info, create one
                    //$userId = 'weChatUser@billyn.net';
                    //$pwd = 'sadfsUdfsZ?@q23!';
                    //在这里获取微信客户的信息，产生一个唯一的userId，取代默认的userId
                    //还需要产生一个密码
                    if (isset($_GET['openid']) && $_GET['openid'] != 'images') {
                        $userOpenId = $_GET['openid'];
                        $userId = $userOpenId . '@billyn.net';
                        $pwd = $userOpenId;
                        $user = NULL;

                        $openIdAttr = BAttribute::find(array('name' => 'wxOpenId', 'value' => $userOpenId, 'ownerType' => 'BUser'), TRUE);
                        if ($openIdAttr) {
                            $savedUserId = $openIdAttr->ownerId;
                            $user = new BUser($savedUserId);
                            $userId = $user->userId;
                            $changedPasswordAttr = $user->getAttribute('changedWechatPassword');
                            if ($changedPasswordAttr) {
                                $pwd = $changedPasswordAttr->getValue();
                            }
                        }

                        //$user = BUser::find(array('userName' => $userId));
                        if (!$user instanceof BUser) {
                            $profile['birthday'] = '01012099';
                            $profile['userName'] = "wechat";
                            $profile['email'] = $userId;
                            $user = BUser::registerWechat($userId, $pwd, $profile);
                            $userId = $user->userId;
                            $user->addAttribute('wxOpenId', $userOpenId);
                            $userInfoTable = new BUserSheet('userInfo');
                            $userInfoData = $profile;
                            $userInfoData['userId'] = $user->getId();
                            $userInfoData['loginId'] = $user->userId;
                            $userInfoData['userName'] = $user->userName;
                            $userInfoData['wxOpenId'] = $userOpenId;
                            $userInfoTable->addList($userInfoData);
                        }

                        $space = $parsedData['wxSpace'];
                        if ($space instanceof BSpace) {
                            $app = $space->getSpaceEngine();
                            //$user = BUser::find(array('userName' => $userId));
                            $role = $app->getRole(BRole::Role_App_customer);
                            if (!$user->isMemberOfRole($role)) {
                                $role->addMember($user);
                                //add wechat user to shared space
                                $attr = $space->getAttribute('config.spaceListForShareWeChatUser');
                                if ($attr instanceof BAttribute) {
                                    $sharingSpaceList = $attr->getValue();
                                    foreach ($sharingSpaceList as $id => $name) {
                                        $space = new BSpace($id);
                                        $app = $space->getSpaceEngine();
                                        $role = $app->getRole(BRole::Role_App_customer);
                                        $role->addMember($user);
                                    }
                                }
                            }
                        }
                        if (Yii::app()->user->isGuest) {
                            BUser::login($userId, $pwd, 0);
                        }
                    }
                }
            }
        }
        //user must login before enter site
        if (Yii::app()->user->isGuest) {
            if (get_class($this) === "SiteController") {
                $this->actionLogin();
                Yii::app()->end();
            } elseif (get_class($this) === 'PublicController') {
                
            } else {
                //setContext will init context for blyn application                
                $this->redirect(array('site/login'));
                Yii::app()->end();
            }
        } else {
            Blyn::app()->getUIManager()->setContext();
        }
    }

    /*
     * 网页授权，我们可以在跳转的网页（网页链接需要在公共号的“OAuth2.0网页授权”里面修改）里面执行getUserInfo($code)函数
     * 
     * 跳转网页里面需要有以下代码
     * $code = $_GET["code"];//获取code
      $userinfo = getUserInfo($code);//获取用户信息，$userinfo为数组，
     * 可以获取   openid	 用户的唯一标识.
     * nickname	 用户昵称
     * sex	 用户的性别，值为1时是男性，值为2时是女性，值为0时是未知
     * province	 用户个人资料填写的省份
     * city	 普通用户个人资料填写的城市
     * country	 国家，如中国为CN
     * headimgurl	 用户头像，最后一个数值代表正方形头像大小（有0、46、64、96、132数值可选，0代表640*640正方形头像），用户没有头像时该项为空
     * privilege	 用户特权信息，json 数组，如微信沃卡用户为（chinaunicom）
     */

    public function getUserInfo($code) {
        $appid = "wxd33a8d04590d6e58";
        $appsecret = "6e18aba904d1e8c71995c5438ebfa4dc";
        //$access_token = "WEIXIN";  //（与基础支持中的access_token不同）
        //根据code获得Access Token
        $access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
        $access_token_json = https_request($access_token_url);
        $access_token_array = json_decode($access_token_json, true);
        $access_token = $access_token_array['access_token'];
        $openid = $access_token_array['openid'];
        //根据Access Token和OpenID获得用户信息
        $userinfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid ";
        $userinfo_json = https_request($userinfo_url);
        $userinfo_array = json_decode($userinfo_json, true);
        return $userinfo_array;
    }

    //获取关注者列表
    public function get_user_list($access_token = NULL, $next_openid = NULL) {
        //$url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=".$this->access_token."&next_openid=".$next_openid;

        $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" . $access_token . "&next_openid=" . $next_openid;
        $res = $this->https_request($url);
        return json_decode($res, true);
    }

    //https请求（支持GET和POST）
    public function https_request($url, $data = null) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    public function isAdminRole() {
        return Yii::app()->user->getState('admin');
    }

    public static function isNullOrEmptyString($question) {
        return (!isset($question) || trim($question) === '');
    }

    public static function dateDiff($d1, $d2) {
        $date_diff = date_diff($d1, $d2);
        $total_days = $date_diff->days;
        $hours = $date_diff->h;
        if ($total_days !== FALSE) {
            $hours += 24 * $total_days;
        }
        $minutes = $date_diff->i;
        $seconds = $date_diff->s;
        return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
    }

    public static function dateDiffHours($d1, $d2) {
        $date_diff = date_diff($d1, $d2);
        $total_days = $date_diff->days;
        $hours = $date_diff->h;
        if ($total_days !== FALSE) {
            $hours += 24 * $total_days;
        }

        return $hours;
    }

    public static function yiiparam($name, $default = null) {
        if (isset(Yii::app()->params[$name]))
            return Yii::app()->params[$name];
        else
            return $default;
    }

    public static function getMapPrefix() {
        $map = Yii::app()->request->getParam('map');
        if ($map == null) {
            $map = Controller::yiiparam('map');
        }

        if ($map == 'qq') {
            return '_qq';
        } else {
            return '';
        }
    }

    protected function beforeRender($view) {
        if (!parent::beforeRender($view)) {
            return false;
        }

        $this->setPageTitle(Yii::t('site', str_replace(Yii::app()->name . ' - ', '', $this->pageTitle)));

        return true;
    }

    /**
     * 发送HTTP请求
     *
     * @param string $url 请求地址
     * @param string $method 请求方式 GET/POST
     * @param string $refererUrl 请求来源地址
     * @param array $data 发送数据
     * @param string $contentType 
     * @param string $timeout
     * @param string $proxy
     * @return boolean
     */
    public static function sendRequest($url, $data, $refererUrl = '', $method = 'GET', $contentType = 'application/json', $timeout = 30, $proxy = false) {
        $ch = null;
        if ('POST' === strtoupper($method)) {
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
            if ($refererUrl) {
                curl_setopt($ch, CURLOPT_REFERER, $refererUrl);
            }
            if ($contentType) {
                curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:' . $contentType));
            }
            if (is_string($data)) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            } else {
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            }
        } else if ('GET' === strtoupper($method)) {
            if (is_string($data)) {
                $real_url = $url . (strpos($url, '?') === false ? '?' : '') . $data;
            } else {
                $real_url = $url . (strpos($url, '?') === false ? '?' : '') . http_build_query($data);
            }

            $ch = curl_init($real_url);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:' . $contentType));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
            if ($refererUrl) {
                curl_setopt($ch, CURLOPT_REFERER, $refererUrl);
            }
        } else {
            $args = func_get_args();
            return false;
        }

        if ($proxy) {
            curl_setopt($ch, CURLOPT_PROXY, $proxy);
        }
        $ret = curl_exec($ch);
        $info = curl_getinfo($ch);
        $contents = array(
            'httpInfo' => array(
                'send' => $data,
                'url' => $url,
                'ret' => $ret,
                'http' => $info,
            )
        );

        curl_close($ch);
        return $ret;
    }

    public static function isSameDay($date1, $date2) {
        return ($date1->format('Y-m-d') == $date2->format('Y-m-d'));
    }

    public static function getDateTime($date = NULL, $time = NULL) {
        if ($date == NULL) {
            $result = new DateTime(date('Y-m-d', time()) . ' ' . $time);
            $result->setTimezone(new DateTimeZone(date_default_timezone_get()));
        } else if ($date instanceof DateTime) {
            if ($time == NULL) {
                $result = $date;
            } else {
                $result = new DateTime($date->format('Y-m-d') . ' ' . $time);
                $result->setTimezone(new DateTimeZone(date_default_timezone_get()));
            }
        } else {
            $result = new DateTime($date . ' ' . $time);
            $result->setTimezone(new DateTimeZone(date_default_timezone_get()));
        }

        return $result;
    }

    public static function loadModel($smodel, $id) {
        $model = $smodel->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    public function afterAction($action) {
        parent::afterAction($action);

        if ($this->runAfterAction) {
            Blyn::app()->runApp();
        }
    }

}
